﻿#include "stdafx.h"
#include "AstType.h"
#include "DefGen.h"
#include "utility.h"
#include "ClassInstanceType.h"
#include "SArrayType.h"

using namespace llvm;
llvm::Value * DefGen::generateCode(llvm::Module *m, llvm::Function *func, llvm::IRBuilder<>&builder)
{
	if (def) {
		if (isClass) return def;
		return def;
	}

	isClass = dynamic_cast<ClassInstanceType*>(type);
	bool isSeq = dynamic_cast<SArrayType*>(type);

	assert(type);
	LLVMContext& context = builder.getContext();
	auto *tp = type->llvmType(context);
	assert(tp);
	auto & block = func->getEntryBlock();

	IRBuilder<> b(&block);

	if (value) {
		llvm::Value* v = value->generateCode(m, func, builder);
		if (isClass) {
			auto *x=PointerType::get(tp, 0);
			def = builder.CreateBitOrPointerCast(v, x, name);
			return def;
		}
		else if (isSeq) { 
			return v;
		}else{
			v = load(builder, v);
			v = try_cast(builder, tp, v);
		}

		// 如果数字，转为指针
		def = b.CreateAlloca(tp, nullptr, name);
		builder.CreateStore(v, def);
	}
	return def;
}

